<?php



namespace App\Model;

use Illuminate\Database\Eloquent\Model;

/**
 * 用户私人资料表
 */
class UserProfilePersonal extends Model
{
    protected $table = 'user_profile_personal';

    protected $fillable = ['flag', 'real_name', 'id_card', 'alipay_account', 'user_id', 'id_card_pics'];

    //待审核
    const STATUS_ING = 0;
    //审核通过
    const STATUS_OK = 1;
    //审核不通过
    const STATUS_FAIL = 2;
    //删除
    const STATUS_DEL = -1;
    //状态
    const STATUS = [
        self::STATUS_ING => '待审核',
        self::STATUS_OK => '审核通过',
        self::STATUS_FAIL => '审核不通过',
        self::STATUS_DEL => '删除'
    ];

    //支付宝
    const BIND_TYPE_ALI = 1;
    //银行卡
    const BIND_TYPE_BANK = 2;

    public function userProfile()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 更新私人资料
     */
    static function updateInfo($userId = 0, $info = [])
    {
        $model = self::where('user_id', $userId)->first();
        if (!$model) $model = new self();
        $model->user_id = $userId;
        $model->real_name = $info['real_name'];
        $model->id_card = $info['id_card'];
        $model->flag = self::STATUS_ING;
        $model->alipay_account = $info['alipay_account'];
        return $model->saveOrFail() ? 1 : 0;
    }

    /**
     * 获取个人资料
     */
    static function getProfile($userId = 0)
    {
        if (!$userId) return [];
        $where = ['user_id' => $userId];
        $item = self::where($where)->first();
        return $item ? $item->toArray() : [];
    }

    /**
     * 获取绑定提现信息
     */
    static function getBindInfo($userId = 0, $type = 'alipay')
    {
        $info = self::where('user_id', $userId)->first();
        if (!$info || $info->flag != self::STATUS_OK) return [];

        if ($info->alipay_account && in_array($type, ['alipay', ''])) {
            return [
                'real_name' => $info->real_name,
                'id_card' => $info->id_card,
                'card_no' => $info->alipay_account,
                'type' => self::BIND_TYPE_ALI
            ];
        }
        if ($info->bank_card && in_array($type, ['bank', ''])) {
            return [
                'real_name' => $info->real_name,
                'id_card' => $info->id_card,
                'card_no' => $info->bank_card,
                'type' => self::BIND_TYPE_BANK
            ];
        }
        return [];
    }

    /**
     * 是否已经刷脸认证
     */
    static function isFaceVerified($userId = 0, $personInfo = [])
    {
        if (!$personInfo) $personInfo = self::getProfile($userId);
        if (!$personInfo) return 0;
        return $personInfo['flag'] == self::STATUS_OK ? 1 : 0;
    }
}
